﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Security.Cryptography;
using System.Text;

namespace Site
{
    public partial class MobileQuery : System.Web.UI.Page
    {
        public string CalculateMD5Hash(string input)
        {
            // step 1, calculate MD5 hash from input
            MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
            byte[] hash = md5.ComputeHash(inputBytes);

            // step 2, convert byte array to hex string
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("x2"));
            }
            return sb.ToString();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string sResponse = "400 Bad Request";

            string sQuery = Request.QueryString["Query"];
            if (sQuery != null)
            {
                if (sQuery == "WT")
                {
                    string sWID = Request.QueryString["WID"];
                    if (sWID != null)
                    {
                        SqlDataSource1.SelectCommand = "SELECT WID FROM Workers WHERE WID='" + sWID + "'";
                        DataView View = (DataView)SqlDataSource1.Select(new DataSourceSelectArguments());
                        if(View.Count == 1)
                            sResponse = View[0]["Worker_Type"].ToString();
                    }
                }
                else if (sQuery == "UQ")
                {
                    string sUser = Request.QueryString["User"];
                    string sPass = Request.QueryString["Pass"];
                    sResponse = "UNKNOWN";
                    if (sUser != null && sPass != null)
                    {
                        SqlDataSource1.SelectCommand = "SELECT * FROM Users WHERE User_Name='" + sUser + "' AND Password='" + CalculateMD5Hash(sPass) + "'";
                        DataView View = (DataView)SqlDataSource1.Select(new DataSourceSelectArguments());
                        if (View.Count == 1)
                            sResponse = "VALID";
                    }

                }
            }

            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.ContentType = "text/plain";
            Response.Write(sResponse);
            Response.End();
        }
    }
}